package com.xieyong.leetcode;

import java.util.HashMap;
import java.util.Map;

public class Leetcode1865 {
    public static void main(String[] args) {
        int[] nums1 = {1, 1, 2, 2, 2, 3};
        int[] nums2 = {1, 4, 5, 2, 5, 4};
        FindSumPairs findSumPairs = new FindSumPairs(nums1,nums2);
        int count = findSumPairs.count(7);// 返回 8 ; 下标对 (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) 满足 2 + 5 = 7 ，下标对 (5,1), (5,5) 满足 3 + 4 = 7
        findSumPairs.add(3, 2); // 此时 nums2 = [1,4,5,4,5,4]
        int count1 = findSumPairs.count(8);// 返回 2 ；下标对 (5,2), (5,4) 满足 3 + 5 = 8
        int count2 = findSumPairs.count(4);// 返回 1 ；下标对 (5,0) 满足 3 + 1 = 4
        findSumPairs.add(0, 1); // 此时 nums2 = [2,4,5,4,5,4]
        findSumPairs.add(1, 1); // 此时 nums2 = [2,5,5,4,5,4]
        int count3 = findSumPairs.count(7);// 返回 11 ；下标对 (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) 满足 2 + 5 = 7 ，下标对 (5,3), (5,5) 满足 3 + 4 = 7
        System.out.println(count);
        System.out.println(count1);
        System.out.println(count2);
        System.out.println(count3);
    }

    static class FindSumPairs {
        private int[] nums1;
        private int[] nums2;
        private Map<Integer,Integer> map = new HashMap<>();

        public FindSumPairs(int[] nums1, int[] nums2) {
            this.nums1 = nums1;
            this.nums2 = nums2;
            for (int i : nums2) {
                map.put(i,map.getOrDefault(i,0) + 1);
            }
        }

        public void add(int index, int val) {
            int oldVal = this.nums2[index];
            int newVal = oldVal + val;
            this.nums2[index] = newVal;
            int oldnum = map.get(oldVal);
            if (oldnum <= 1) {
                map.remove(oldVal);
            } else {
                map.put(oldVal,oldnum - 1);
            }
            map.put(newVal,map.getOrDefault(newVal,0) + 1);
        }

        public int count(int tot) {
            int res = 0;
            for (int i : nums1) {
                int k = tot - i;
                res += map.getOrDefault(k,0);
            }
            return res;
        }
    }
}
